package com.lyf.boot.listener;

import com.lyf.boot.constant.TioConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.WsTioServerListener;

/**
 * @author Luyufan
 * @date 2025/1/14
 **/
@Slf4j
@Component
public class TioServerListener extends WsTioServerListener {

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        super.onAfterConnected(channelContext, isConnected, isReconnect);
        log.info("onAfterConnected\r\n{}", channelContext);
    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
        super.onAfterSent(channelContext, packet, isSentSuccess);
        log.info("onAfterSent\r\n{}\r\n{}", packet.logstr(), channelContext);
    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        super.onBeforeClose(channelContext, throwable, remark, isRemove);
        log.info("onBeforeClose\r\n{}", channelContext);
        WsSessionContext wsSessionContext = (WsSessionContext) channelContext.get();
        if (wsSessionContext != null && wsSessionContext.isHandshaked()) {

            int count = Tio.getAll(channelContext.tioConfig).getObj().size();

            String msg = channelContext.getClientNode().toString() + " 离开了，现在共有【" + count + "】人在线";
            //用tio-websocket，服务器发送到客户端的Packet都是WsResponse
            WsResponse wsResponse = WsResponse.fromText(msg, TioConstant.CHARSET);
            //群发
            Tio.sendToGroup(channelContext.tioConfig, "1", wsResponse);
        }
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {
        super.onAfterDecoded(channelContext, packet, packetSize);
        log.info("onAfterDecoded\r\n{}\r\n{}", packet.logstr(), channelContext);
    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {
        super.onAfterReceivedBytes(channelContext, receivedBytes);
        log.info("onAfterReceivedBytes\r\n{}", channelContext);
    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {
        super.onAfterHandled(channelContext, packet, cost);
        log.info("onAfterHandled\r\n{}\r\n{}", packet.logstr(), channelContext);
    }
}
